//
//  LTPersonInformationVC.m
//  Learn
//
//  Created by zyl_macbookpro on 2024/4/1.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "LTPersonInformationVC.h"
#import <Photos/Photos.h>
#import "LTMineAPIManager.h"
@interface LTPersonInformationVC ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic ,strong)UITableView *tableView;

@property(nonatomic ,strong)UIImageView *headerImgView;

@property(nonatomic ,strong)UIButton *logoButton;

@property(nonatomic ,strong)NSArray *titleArray;

@property(nonatomic ,strong)YYLabel *protocolLabel;

@property(nonatomic ,strong)NSString *nickName;

@property(nonatomic ,strong)NSString *avatar;

@property(nonatomic ,strong)NSString *schoolName;

@property(nonatomic ,strong)NSString *gradeName;

@property(nonatomic ,strong)NSString *mobile;

@property(nonatomic ,strong)NSString *username;

@property (nonatomic ,strong)UIImagePickerController *headerImagePickerController;
@end

@implementation LTPersonInformationVC
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self renderNavBarWithBackgroundImage:[UIImage imageWithColor:LTClearColor] backgroundColor:LTClearColor shadowColor:nil textAttributeDic:@{NSForegroundColorAttributeName:rgba(0, 0, 0, 1),NSFontAttributeName:MFontWithSize(17)} enableScrollEdgeAppearance:NO];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"个人信息";
    // Do any additional setup after loading the view.
    [self setBackButtonIsHidden:NO];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.logoButton];
    self.view.backgroundColor = rgba(247, 248, 250, 1);
    self.tableView.height = self.titleArray.count *55+10;
    [self getUserInfo];
}
#pragma mark - api
- (void)getUserInfo
{
    [LTMineAPIManager getUserInfoWithParam:@{} result:^(NSDictionary * _Nonnull dic) {
        NSDictionary *data = dic[@"data"];
        self.nickName = data[@"nickname"];
        self.username = data[@"username"];
        self.avatar = data[@"avatar"];
        self.mobile = data[@"mobile"];
        self.schoolName = data[@"school"][@"name"];
        self.gradeName = data[@"grade"][@"gradeName"];
        [self.tableView reloadData];
    }];
}

- (void)uploadHeaderImg
{
    NSData *imageData;
    imageData = UIImageJPEGRepresentation(self.headerImgView.image, .5f);
    UIImage *img = [UIImage imageWithData:imageData];
    [LTMineAPIManager upLoadHeadImageWithParam:@{@"img":img} result:^(NSDictionary * _Nonnull dic) {
        if (dic[@"data"][@"fullurl"]) {
            [self changePersonInfoWithParame:@{@"avatar":dic[@"data"][@"fullurl"]}];
        }
    }];
}
- (void)changePersonInfoWithParame:(NSDictionary *)parame
{
    [LTMineAPIManager changeUserInfoWithParam:parame result:^(NSDictionary * _Nonnull dic) {
        [self getUserInfo];
    }];
}
#pragma mark -UITableViewDelegate,UITableViewDelegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@""];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    
    cell.detailTextLabel.textColor = LTTextBlack;
    cell.accessoryView = [[UIImageView alloc] initWithImage:IMAGENAMED(@"ic_right_arrow_gray")];
    if ([self.titleArray[indexPath.row] isEqualToString:@"头像"]) {
        [cell addSubview:self.headerImgView];
        if ([self.avatar hasPrefix:@"http"]) {
            NSURL *url = [NSURL URLWithString:self.avatar];
            [self.headerImgView sd_setImageWithURL:url];
        }
        cell.detailTextLabel.text = @"";
    }
    if ([self.titleArray[indexPath.row] isEqualToString:@"姓名"]) {
        cell.accessoryView = nil;
        cell.detailTextLabel.text = self.nickName;
    }
    if ([self.titleArray[indexPath.row] isEqualToString:@"账号"]) {
        cell.accessoryView = nil;
        cell.detailTextLabel.text = self.username;
    }
    if ([self.titleArray[indexPath.row] isEqualToString:@"修改密码"]) {
        cell.detailTextLabel.text = @"";
    }
    if ([self.titleArray[indexPath.row] isEqualToString:@"手机号"]) {
        cell.detailTextLabel.text = self.mobile;
    }
    if ([self.titleArray[indexPath.row] isEqualToString:@"学校"]) {
        cell.detailTextLabel.text = self.schoolName;
        cell.accessoryView = nil;
    }
    cell.textLabel.text = self.titleArray[indexPath.row];
    cell.textLabel.font = MFontWithSize(16);
    cell.textLabel.textColor = LTTextBlack;
    cell.detailTextLabel.font = RFontWithSize(15);
    
    
   
    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.titleArray.count;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 65;
    }
    return 55;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.titleArray[indexPath.row] isEqualToString:@"头像"]) {
        [self alert];
    }
    if ([self.titleArray[indexPath.row] isEqualToString:@"修改密码"]) {
        
        [self pushToViewControllerWithClassName:@"LTChangePwdViewController" animated:YES];
        
    }
    if ([self.titleArray[indexPath.row] isEqualToString:@"手机号"]) {
        
        [self pushToViewControllerWithClassName:@"LTMyPhoneViewController" animated:YES];
        
    }
}
- (void)logoButtonAction
{
    [LTApp goLogin];
}
#pragma mark -private
#pragma mark 打开相机 或者相册

-(void)openCamera:(BOOL)isCamera
{
    if (isCamera) {
        /* 打开相机 */
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (granted)
                {
                    /* 打开相册 */
                    self.headerImagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                    self.headerImagePickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto; //自动闪关
                    [self presentViewController:self.headerImagePickerController animated:YES completion:nil];
                }
                else{
                }
            });
        }];
    }
    else{
        dispatch_async(dispatch_get_main_queue(), ^{
            /* 打开相册 */
            self.headerImagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:self.headerImagePickerController animated:YES completion:nil];
        });
    }
}
- (void)alert{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"相机"
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera:YES];
                                                         }];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相册"
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera:NO];
                                                         }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * _Nonnull action) {
       
                                                         }];
    [alertController addAction:cameraAction];
    [alertController addAction:photoAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    self.headerImgView.image = info[UIImagePickerControllerEditedImage];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        dispatch_async(dispatch_get_main_queue(), ^{
            [self uploadHeaderImg];
            [self.headerImagePickerController dismissViewControllerAnimated:YES completion:nil];
        });
    });
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.headerImagePickerController dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark -getters and setters
-(UITableView *)tableView{
    if (!_tableView){
        _tableView =[[UITableView alloc] initWithFrame:CGRectMake(16, LTTopBarHeight + 16, LTScreenWidth - 32, LTScreenHeight - LTTopBarHeight - LTBottomDangerousAreaHeight - 60) style:UITableViewStylePlain];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        _tableView.bounces = NO;
        [_tableView setBackgroundColor:LTWhiteColor];
        [_tableView setSeparatorColor:LTSeparatorColor];
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0, 10, 0, 0)];
       
        _tableView.layer.cornerRadius = 12;
        _tableView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:50/255.0 blue:83/255.0 alpha:0.0500].CGColor;
        _tableView.layer.shadowOffset = CGSizeMake(0,2);
        _tableView.layer.shadowOpacity = 1;
        _tableView.layer.shadowRadius = 12;

    }
    
    return _tableView;
}
- (NSArray *)titleArray
{
    if (!_titleArray) {
        _titleArray = @[@"头像",@"姓名",@"账号",@"修改密码",@"手机号",@"学校"];
    }
    return _titleArray;
}
-(UIImagePickerController *)headerImagePickerController{
    if (!_headerImagePickerController) {
        _headerImagePickerController = ({
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; //相机或者图库
            imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical; //转场动画
            imagePickerController.allowsEditing = YES; //允许编辑，设为NO则直接选中，YES可以调整位置
            imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh; //拍摄的照片质量，用于不同网络状态下，比如wifi下发送高、中质量的图片，蜂窝数据下发送低质量的图片，默认中等
            if (imagePickerController.sourceType == UIImagePickerControllerSourceTypeCamera) {
                imagePickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto; //自动闪关
            }

            imagePickerController;
        });
        _headerImagePickerController.delegate = self;
    }
    return _headerImagePickerController;
}

- (UIImageView *)headerImgView
{
    if (!_headerImgView) {
        _headerImgView = [[UIImageView alloc] initWithFrame:CGRectMake(LTScreenWidth - 32 - 70, 13, 36, 36)];
        //_headerImgView.backgroundColor = lRedColor;
        [_headerImgView setAllCornersWithCornerRadius:18];
    }
    return _headerImgView;
}
-(UIButton *)logoButton
{
    if (!_logoButton)
    {
        _logoButton = [UIButton new];
        _logoButton.frame =CGRectMake(32, LTScreenHeight - LTBottomDangerousAreaHeight - 60, LTScreenWidth - 64, 44);
       
        [_logoButton setTitle:@"退出登录" forState:UIControlStateNormal];
       // [_logoButton setTitleColor:rgba(181, 181, 181, 1) forState:UIControlStateNormal];
        [_logoButton setTitleColor:LTWhiteColor forState:UIControlStateNormal];
        [_logoButton.titleLabel setFont:MFontWithSize(14)];
        [_logoButton addTarget:self action:@selector(logoButtonAction) forControlEvents:UIControlEventTouchUpInside];
        _logoButton.backgroundColor = rgba(41, 121, 255, 1);
        _logoButton.layer.cornerRadius = 22;
        _logoButton.layer.shadowColor = rgba(41, 121, 255, 0.50).CGColor;
        _logoButton.layer.shadowOffset = CGSizeMake(0,4);
        _logoButton.layer.shadowOpacity = 1;
        _logoButton.layer.shadowRadius = 6;
    }
    
    return _logoButton;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
